﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;

namespace PSE.Tools.CadastroMensagens.Autenticacao
{
    public class AutenticacaoAD
    {
        private string _path;
        private string _filterAttribute;

        private AutenticacaoAD() { }
        private static object _objLock = new object();
        private static AutenticacaoAD _instancia;
        public static AutenticacaoAD Instancia
        {
            get
            {
                lock (_objLock)
                {
                    if (_instancia == null)
                        _instancia = new AutenticacaoAD();
                }
                return _instancia;
            }
        }

        public AutenticacaoAD(string path)
        {
            _path = path;
        }

        public bool EstaAutenticado(string dominio, string usuario, string senha)
        {
            bool logou = false;
            try
            {
                if (!string.IsNullOrEmpty(dominio))
                    usuario = dominio + "\\" + usuario;
                DirectoryEntry entrada = new DirectoryEntry(_path, usuario.Trim(), senha.Trim());
                _filterAttribute = entrada.Name;
                logou = true;
            }
            catch (Exception ex)
            {
                logou = false;
            }
            return logou;
        }

        public string Grupos()
        {
            DirectorySearcher search = new DirectorySearcher(_path);
            search.Filter = "(cn=" + _filterAttribute + ")";
            search.PropertiesToLoad.Add("memberOf");
            StringBuilder groupNames = new StringBuilder();

            try
            {
                SearchResult result = search.FindOne();
                int propertyCount = result.Properties["memberOf"].Count;
                string dn;
                int equalsIndex, commaIndex;

                for (int propertyCounter = 0; propertyCounter < propertyCount; propertyCounter++)
                {
                    dn = (string)result.Properties["memberOf"][propertyCounter];
                    equalsIndex = dn.IndexOf("=", 1);
                    commaIndex = dn.IndexOf(",", 1);
                    if (-1 == equalsIndex)
                    {
                        return null;
                    }
                    groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1));
                    groupNames.Append("|");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error obtaining group names. " + ex.Message);
            }
            return groupNames.ToString();
        }
    }
}
